/**
 * 
 */
package org.gbif.agi.service.impl;

import java.util.List;

import org.appfuse.service.impl.GenericManagerImpl;
import org.gbif.agi.dao.GenusDao;
import org.gbif.agi.model.Genus;
import org.gbif.agi.model.GenusRelationship;
import org.gbif.agi.model.GenusUsage;
import org.gbif.agi.service.GenusManager;

/**
 * @author timrobertson
 */
public class GenusManagerImpl extends GenericManagerImpl<Genus, Long> implements
		GenusManager {
	private GenusDao genusDao;
	private int autocompleteResults = 10;
	private int searchResults = 100;

	public GenusManagerImpl(GenusDao genusDao) {
		super(genusDao);
		this.genusDao = genusDao;
	}
	
	/**
	 * @see org.gbif.agi.service.GenusManager#getDetailed(java.lang.String)
	 */
	public List<Genus> getDetailed(String startsWith) {
		List<Genus> genera = genusDao.findByStartingWith(startsWith, searchResults);
		// preload the stuff
		// TODO - perhaps move to a single query ja?
		// or ajaxy it up?
		for (Genus g : genera) {
			populateGenus(g);			
		}
		return genera;
	}

	
	/**
	 * @see org.gbif.agi.service.GenusManager#getDetailed(java.lang.String)
	 */
	public Genus getDetailed(long id) {
		Genus genus = get(id);
		populateGenus(genus);
		return genus;
	}
	
	/**
	 * TODO this is pretty awful coding, but just to get stuff working quickly...
	 * @param g To populate
	 */
	private void populateGenus(Genus g) {
		loadUsage(g);
		for (GenusRelationship r : g.getFromRelationships()) {
			log.info("Populating genus: " + r.getToGenus().getFullScientificName());
			r.getToGenus();
			loadUsage(r.getToGenus());
			r.getDeletionUser();
			r.getAlgorithm();
			r.getAgiDatasource();
			r.getRelationshipType();
			r.getUser();				
		}
		for (GenusRelationship r : g.getToRelationships()) {
			log.info("Populating genus: " + r.getFromGenus().getFullScientificName());
			r.getFromGenus();
			loadUsage(r.getFromGenus());
			r.getDeletionUser();
			r.getAlgorithm();
			r.getAgiDatasource();
			r.getRelationshipType();
			r.getUser();
		}			
	}

	private void loadUsage(Genus g) {
		List<GenusUsage> usages = g.getGenusUsages();
		for (GenusUsage usage : usages) {
			usage.getAgiDatasource();
			usage.getRemoteId();
		}
	}
	
	/**
	 * @see org.gbif.agi.service.GenusManager#getSuggestions(java.lang.String)
	 */
	public List<Genus> getSuggestions(String startsWith) {
		return genusDao.findByStartingWith(startsWith, autocompleteResults);
	}

	public int getAutocompleteResults() {
		return autocompleteResults;
	}

	public void setAutocompleteResults(int autocompleteResults) {
		this.autocompleteResults = autocompleteResults;
	}

	public GenusDao getGenusDao() {
		return genusDao;
	}

	public void setGenusDao(GenusDao genusDao) {
		this.genusDao = genusDao;
	}
}
